package com.kuaigou.cim.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.farsunset.cim.nio.mutual.Message;
import com.farsunset.cim.nio.mutual.SentBody;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public final class JSONHelper {

	/**
	 * 将字符串转成实体类，允许斜杠等字符串
	 */
	public static <T> T jsonToEntity(String json, Class<T> clazz)
			throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		// 允许反斜杆等字符
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
		return mapper.readValue(json, clazz);
	}
	
	public static <T> List<T> jsonToList(String json, Class<T> clazz)
			throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		// 允许反斜杆等字符
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
		JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, clazz);  		
		return mapper.readValue(json, javaType);
	}


	/**
	 * 实体类转JSON字符串
	 */
	public static String entityToJson(Object entity) {
		return JSON.toJSONString(entity);
	}

	/**
	 * 将字符串转成JsonNode，允许斜杠等字符串
	 */
	public static JsonNode jsonToJsonNode(String json) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		// 允许反斜杆等字符
		mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
		// 允许单引号
		mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
		return mapper.readValue(json, JsonNode.class);
	}

	public static <T> String objectToJson(Object object, Class<T> cls)
			throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerSubtypes(cls);
		String reqJson = mapper.writeValueAsString(object);
		return reqJson;
	}	
	
	public static void main(String[] args) {
		String a = "{\"key\":\"a\",\"data\":{\"ddd\":\"ttt\",\"ggg\":\"hhh\"},\"timestamp\":11111111}";
		String b = "{\"key\":\"a\",\"timestamp\":11111111}";
		Message message = new Message();
		SentBody body = null;
		try {
//			 body = (SentBody)JSONHelper.jsonToEntity(a, SentBody.class);
			message.setMapStr(b);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
	}

}